package com.stars.easyms.redis.interceptor;

import com.stars.easyms.base.util.ReflectUtil;
import com.stars.easyms.redis.annotion.RedisHashLength;
import com.stars.easyms.redis.exception.RedisInterceptorException;
import org.aopalliance.intercept.MethodInvocation;

import java.lang.reflect.Method;

/**
 * <p>className: RedisHashLengthInterceptor</p>
 * <p>description: redis的hash类型的长度注解拦截器</p>
 *
 * @author guoguifang
 * @version 1.7.2
 * @date 2021/1/21 5:16 下午
 */
public class RedisHashLengthInterceptor extends AbstractRedisInterceptor<RedisHashLength> {

    @Override
    Object invoke(MethodInvocation methodInvocation, RedisHashLength redisHashLength) throws RedisInterceptorException {
        if (isEnabled()) {
            String redisKey = getRedisKey(methodInvocation, redisHashLength.group());
            Long hashSize = easyMsRedisTemplate.hashSize(redisKey);

            // 如果获取到的长度不为null那么判断是否是int类型，如果是则强转成int类型
            if (hashSize != null) {
                Method pointMethod = methodInvocation.getMethod();
                Class<?> returnType = pointMethod.getReturnType();
                if (Long.class.equals(returnType)) {
                    return hashSize;
                } else if (Integer.class.equals(returnType)) {
                    return hashSize.intValue();
                } else {
                    logger.error("Method '{}' returnType should be Integer or Long!", ReflectUtil.getMethodFullName(pointMethod));
                }
            }
        }
        return proceed(methodInvocation);
    }

}